<template>
  <el-select
    v-model="name"
    ref="selector"
    :multiple="multiple"
    :disabled="disabled"
    remote
    clearable
    :allow-create="params.allowCreate || false"
    :placeholder="
      params.placeholder
        ? $t(params.placeholder)
        : apiModule
        ? $t('请输入')
        : $t('请选择')
    "
    :remote-method="handleRemoteMethod"
    :loading="remoteLoading"
    popper-class="vxe-table--ignore-clear"
    class="remote_select"
    @visible-change="changeFocus"
    :collapse-tags="multiple && !hidCollapseTags"
    @change="handleRemoteChange"
    @keyup.enter="handleSearch"
    @clear="handleClear"
    @popupScroll="setupScrollListener"
  >
    <template #header>
      <div class="select-header">
        <el-input
          ref="inputInsideSelect"
          v-model.lazy="inputName"
          :debounce="500"
          :allow-create="params?.allowCreate || false"
          clearable
          :prefix-icon="Search"
          @change="
            () => {
              !remoteType ? handleRemoteChange : '';
            }
          "
          @input="handleInput"
        />
        <el-button
          v-if="params.type === 'advanced-select'"
          class="btn"
          round
          @click="dialogVisible = true"
          >{{ $t("高级检索") }}</el-button
        >
      </div>
    </template>
    <el-option
      v-for="it in remoteOptions"
      :key="it.id || it[params?.code || params.name]"
      :disabled="it.disabled"
      :label="it[params.name]"
      :value="it[params.keyValue] || it[params.name]"
    >
      <div
        v-if="params.showCustomizedOption && !hideCustomizedOption"
        class="option-outer-div"
      >
        <div class="option-label option-name">
          <div>{{ it[params.nameKey || params.name] }}</div>
          <div>{{ it[params.abbreviation] }}</div>
        </div>
        <div class="option-label option-info">
          {{ display(it) }}
        </div>
      </div>
    </el-option>
    
    <!-- 滚动加载状态指示器 -->
    <div v-if="props.infiniteScroll && (loadingMore || !hasMore)" class="scroll-loading">
      <div v-if="loadingMore" class="loading-text">
        <el-icon class="is-loading"><Loading /></el-icon>
        {{ $t("加载中...") }}
      </div>
      <div v-else-if="!hasMore && remoteOptions.length > 0" class="no-more-text">
        {{ $t("没有更多数据了") }}
      </div>
    </div>
  </el-select>
  <AdvancedSelectDialog
    v-if="dialogVisible"
    :customerZhName="inputName"
    :fixedParams="params.fixedParams"
    :apiModule="apiModule"
    v-model:visible="dialogVisible"
    @on-submit="handleRemoteChange"
  />
</template>
<script setup>
import { onMounted, ref, watch, nextTick } from "vue";
import { Search, Loading } from "@element-plus/icons-vue";
import { debounce } from "@/utils/mUtils";
import i18n from "@/lang/index";
defineOptions({
  name: "RemoteSelect",
  inheritAttrs: false,
});
const props = defineProps({
  params: {
    type: Object,
    default: null,
  },
  multiple: Boolean,
  disabled: Boolean,
  apiModule: {
    type: Function,
    required: true,
  },
  names: {
    type: String,
    default: "",
  },
  remoteType: {
    type: Boolean,
    default: false,
  },
  validateEvent: {
    type: Boolean,
    default: true,
  },
  hidCollapseTags: {
    type: Boolean,
  },
  readonly: Boolean,
  formData: {
    type: Object,
    default: () => ({}),
  },
  // 滚动加载相关props
  infiniteScroll: {
    type: Boolean,
    default: true,
  },
  pageSize: {
    type: Number,
    default: 20,
  },
});
const dialogVisible = ref(false);
const name = ref("");
const inputName = ref("");
const selector = ref();
const inputInsideSelect = ref();
const remoteLoading = ref(false);
const remoteOptions = ref([]);
const hideCustomizedOption = ref(false);

// 滚动加载相关状态变量
const currentPage = ref(1);
const hasMore = ref(true);
const loadingMore = ref(false);
const currentQuery = ref("");
const emit = defineEmits([
  "input",
  "handleRemoteChange",
  "handleSearch",
  "handleClear",
]);
watch(
  () => props.names,
  (newVal) => {
    name.value = newVal;
  },
  { immediate: true }
);

watch(
  () => name.value,
  (newVal, val) => {
    if (!props.params.queryId) inputName.value = newVal;
  },
  {
    immediate: true,
  }
);
onMounted(() => {
  handleRemoteMethod(name.value);
});
// 给input防抖调用后端api
const handleInput = debounce((value) => {
  handleRemoteMethod(value);
}, 500);

// 设置滚动监听器
const setupScrollListener = () => {
  const selectDropdown = selector.value?.popperRef?.querySelector('.el-select-dropdown .el-select-dropdown__wrap');
  if (selectDropdown) {
    selectDropdown.addEventListener('scroll', handleScroll);
  }
};

// 处理滚动事件
const handleScroll = (event) => {
  if (!props.infiniteScroll || loadingMore.value || !hasMore.value) return;
  
  const { scrollTop, scrollHeight, clientHeight } = event.target;
  
  // 当滚动到底部附近时触发加载更多
  if (scrollTop + clientHeight >= scrollHeight - 10) {
    loadMoreData();
  }
};

// 加载更多数据
const loadMoreData = async () => {
  if (loadingMore.value || !hasMore.value) return;
  
  loadingMore.value = true;
  currentPage.value++;
  
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: props.pageSize,
    };
    
    if (currentQuery.value) {
      params[props.params.searchKey] = currentQuery.value;
    }
    
    // 固定参数
    if (props.params.dynamicParameter) {
      for (let key in props.params.dynamicParameter) {
        const value = props.params.dynamicParameter[key];
        params[key] = props.formData[value];
      }
    }
    const { rows, data, total } = await props.apiModule({
      ...params,
      ...props.params.fixedParams,
    });
    
    const newData = rows || data;
    if (newData && newData.length > 0) {
      remoteOptions.value = [...remoteOptions.value, ...newData];
      
      // 检查是否还有更多数据
      const totalCount = total || newData.length;
      const currentCount = remoteOptions.value.length;
      hasMore.value = currentCount < totalCount;

      
    } else {
      hasMore.value = false;
    }
  } catch (error) {
    console.error('加载更多数据失败:', error);
    hasMore.value = false;
  } finally {
    loadingMore.value = false;
  }
};

const handleSearch = (event) => {
  if (event.key === "Enter" && event.ctrlKey) {
    // 阻止默认行为，即提交表单
    event.preventDefault();
    // 执行相应的操作
    emit("handleSearch");
  }
};
async function handleRemoteMethod(query) {
  console.log(inputName.value,'-=---');
  
  hideCustomizedOption.value = false;
  remoteLoading.value = true;
  
  // 保存当前查询条件
  currentQuery.value = query;
  
  // 重置分页状态
  currentPage.value = 1;
  hasMore.value = true;
  
  const params = {};

  if (Array.isArray(query) && query.length) {
    query = "";
  }
  
  if (inputName.value) {
    params[props.params.searchKey] = query;
  } else {
    params["id"] = query;
  }

  // 如果启用滚动加载，添加分页参数
  if (props.infiniteScroll) {
    params.pageNum = currentPage.value;
    params.pageSize = props.pageSize;
  }

  // 固定参数
  if (props.params.dynamicParameter) {
    for (let key in props.params.dynamicParameter) {
      const value = props.params.dynamicParameter[key];
      params[key] = props.formData[value];
    }
  }
  
  try {
    const { rows, data, total } = await props.apiModule({
      ...params,
      ...props.params.fixedParams,
    });
    remoteOptions.value = rows || data;

    // 处理禁用选项
    remoteOptions.value.forEach((el) => {
      if (props.params.disabledList?.includes(el[props.params.name])) {
        el.disabled = true;
      }
    });
    // 如果启用滚动加载，检查是否还有更多数据
    if (props.infiniteScroll) {
      const totalCount = total || remoteOptions.value.length;
      hasMore.value = remoteOptions.value.length < totalCount;
    }
    
    remoteLoading.value = false;
  } catch {
    remoteLoading.value = false;
    hasMore.value = false;
  }
  
  if (remoteOptions.value.length === 0) {
    // 当模糊查询是可创建值时，没搜索到可创建
    if (props.params.allowCreate) {
      remoteOptions.value.push({ [props.params.name]: inputName.value });
    }
    // 查不到值时，插入一个不可选的下拉框内容解决下拉框消失的问题（selector 组件定义死的判断）
    else {
      hideCustomizedOption.value = true;
      remoteOptions.value.push({
        [props.params.name]: i18n.global.t("无匹配数据"),
        disabled: true,
      });
    }
  }
  
  // 重新设置滚动监听器
  if (props.infiniteScroll) {
    nextTick(() => {
      setupScrollListener();
    });
  }
  
  inputInsideSelect.value.focus();
}
function handleRemoteChange(val) {
  if(!val) return
  if (val && typeof val === "object") {
    emit("handleRemoteChange", val);
  } else {
    const row = remoteOptions.value.find(
      (it) => it[props.params.keyValue || props.params.name] === val
    );
    if (!row) {
      name.value = "";
    }
    emit("handleRemoteChange", val, row);
  }
}
function changeFocus(val) {
  if (val) {
    handleRemoteMethod(inputName.value || "");
  } else {
    // 字段存在选中值时，赋值给下拉框内的输入框
    if (!props.params.queryId) inputName.value = name.value || "";
  }
}
function handleClear() {
  emit("handleClear");
}
function display(it) {
  const str = [];
  if (props.params.displayKey) {
    for (const key in props.params.displayKey) {
      let st = it[props.params.displayKey[key]];
      if (props.params.displayName && props.params.displayName[key]) {
        st = props.params.displayName[key][it[props.params.displayKey[key]]];
      }
      st && str.push(st);
    }
  }
  return str.join(props.params.symbol || "/");
}
</script>
<style lang="scss" scoped>
.select-header {
  display: flex;

  :deep() .el-input .el-input__wrapper {
    width: 332px;
    height: 26px;
    // margin-right: 16px;
    border: 1px solid #dcdcdc;
    border-radius: 15px !important;
  }

  .btn {
    width: 92px;
    height: 26px;
    margin-left: 16px;
    border: 1px solid #dcdcdc;
    border-radius: 13px;

    .span {
      width: 52px;
      height: 18px;
      font-size: 13px;
      font-style: normal;
      font-weight: 500;
      line-height: 18px;
      color: #333;
      text-align: right;
      text-transform: none;
    }
  }
}

/* 将第偶数行的选项颜色改为淡灰色 */
// .el-select-dropdown__item:nth-child(odd) {
//   background-color: #f9f9fb;
// }

.el-select-dropdown__item:has(.option-outer-div) {
  /* 父元素拥有 .option-outer-div 类的样式设置
   * 仅在 .el-select-dropdown__item 类里包含 .option-outer-div 类的情况下，才会应用此样式
  */
  height: 62px;
  padding: 10px 20px;
  line-height: 62px;
}

.option-name {
  display: flex;
  justify-content: space-between;
}

.option-label {
  margin-bottom: 5px;
  font-weight: 500;
  line-height: 18px;
  color: #333f;
}

.option-info {
  font-weight: 400;
  color: #666f;
}

/* 滚动加载相关样式 */
.scroll-loading {
  padding: 8px 0;
  text-align: center;
  border-top: 1px solid #f0f0f0;
}

.loading-text {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
  
  .el-icon {
    margin-right: 4px;
    animation: rotating 2s linear infinite;
  }
}

.no-more-text {
  color: #c0c4cc;
  font-size: 12px;
}

@keyframes rotating {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
